# coding:utf-8

from flask import request, jsonify
from flask_restful import Resource

from app.token import AuthToken
from .codes import SUCCESS, UNAUTHORIZED


class Response(object):
    """
    created by chenhj at 2017/8/11
    """
    def __new__(cls, code=SUCCESS, info_dict=None):
        resp = {
            'status': code.status,
            'msg': code.msg,
        }
        if info_dict:
            resp.update(info_dict)
        return resp


class UnauthException(Exception):
    """
    created by chenhj at 2017/8/11
    未登录的返回码需要以异常去抛出
    """


class AuthResource(Resource):
    """
    created by chenhj at 2017/8/10
    所有需要登录的都先继承此资源
    """
    def load_user(self):
        token = request.cookies.get('opc_token')
        if not token:
            raise UnauthException
        user = AuthToken.verify_auth_token(token)
        if not user:
            raise UnauthException
        return user

    def dispatch_request(self, *args, **kwargs):
        try:
            self.user = self.load_user()
        except UnauthException:
            resp = jsonify(Response(UNAUTHORIZED))
            resp.delete_cookie('opc_token')
            return resp
        return super(AuthResource, self).dispatch_request(*args, **kwargs)
